package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    // 分类列表
    @GetMapping("/category/list")
    public ResultInfo findAll() {
        List<Category> list = null;

        // 先查询缓存
        String categoryKey = "category_list";

        if (redisTemplate.hasKey(categoryKey)) {
            list = (List<Category>) redisTemplate.opsForValue().get(categoryKey);
            log.info("查询redis缓存");
        } else {
            // 调用service查询MySQL
            list = categoryService.findAll();
            log.info("查询MySQL数据库");
            // 同步到redis中
            redisTemplate.opsForValue().set(categoryKey, list);
        }

        // 返回结果
        return ResultInfo.success(list);
    }
}